import { ProxyUser, ProxyType } from '../ml/proxy_user';
import { V, Connection } from 'x-engine';
import { X } from "x-orm";
import { failed, SetCache, UUID, success } from '../../../lib/utils';
import { md5 } from 'locutus/php/strings';
import { time } from 'locutus/php/datetime';
import { ProxyMember } from '../ml/proxy_member';
import { BindAccount } from '../ml/bind_account';
import { ProxyCash, CashStatus } from '../ml/proxy_cash';

@V.Controller({
    type: Connection.HTTP,
    url: "/proxy/api/:method",
    dataType: "json",
    authorization: ['proxy']
})
export class ProxyAuthAPI {
    /**
     * 得到所有的下级代理
     */
    async get_children_proxy(proxyUser: ProxyUser) {
        const list = X.of(ProxyUser).find({
            where: {
                parent_id: proxyUser.id
            }
        });
        return list;
    }


    /**
     * 编辑代理
     */
    async editJingji(
        proxyUser: ProxyUser,
        body: ProxyUser,
    ) {

        if (!body.parent_id)
            body.parent_id = proxyUser.id;


        //密码加密
        // body.password = md5(body.password); 
        if (!body.id) {
            body.add_time = time();

            const user = await X.of(ProxyUser).findOne({
                where: {
                    name: body.name
                }
            });

            if (user) {
                return failed("已有同名会员");
            }
        }

        if(body.dj_money < 0 || body.limit_money < 0){
            return failed("参数错误");
        }

        try {
            console.log(body)
            await X.of(ProxyUser).save(body);
            return success();
        }
        catch (e) {
            console.log(e)
            return failed();
        }
    }

    /**
     * 客户管理-编辑
     * @param proxyUser 
     * @param body 
     */
    async editMember(
        proxyUser: ProxyUser,
        body: ProxyMember
    ) {
        body.parent_id = proxyUser.id;
        //查询手机号是否存在
        if (!body.id) {
            const count = await X.of(ProxyMember).count({
                where: {
                    phone: body.phone
                }
            });
            if (count) {
                return failed();
            }

            body.add_time = time();
        }
        try {
            await X.of(ProxyMember).save(body);
            return success();
        }
        catch (e) {
            return failed();
        }
    }


    async modify_password(
        proxyUser: ProxyUser,
        id: number,
        pass: string,
        type?
    ) {
        if (!type) {
            type = 'login';
        }
        //验证授权
        const user = await X.of(ProxyUser).findOne(id);
        if (!user) {
            return failed();
        }
        if (user.parent_id != proxyUser.id) {
            return failed();
        }
        if (pass.length < 6) {
            return failed();
        }
        if (type == 'login') {
            user.password = pass;
        }
        else {
            user.pay_password = pass;
        }
        await X.save(user);
        return success();
    }

    /**
     * 签约
     */
    async bind_account(
        proxyUser : ProxyUser,
        body : BindAccount
    ){
        let flag = await X.of(BindAccount).count({
            where : {
                proxy_id : proxyUser.id
            }
        });
        if(flag){
            return failed();
        }
        //校验支付密码
        const paypass = (body as any).pay_password; 
        flag = await X.of(ProxyUser).count({
            where : {
                pay_password : paypass
            }
        });
        if(!flag){
            return failed('支付密码错误！');
        }

        try{
            const paypass = (body as any).pay_password;
            delete ((body as any).pay_password);
            body.proxy_id = proxyUser.id;
            await X.of(BindAccount).save(body);
            return success();
        }
        catch(e){
            return failed();
        }
    }

    /**
     * 接触签约
     */
    async unbind_account(
        proxyUser : ProxyUser
    ){
        await X.of(BindAccount).delete({
            proxy_id : proxyUser.id
        })
    }


    //左侧菜单
    navs(proxyUser: ProxyUser) {

        const ret: any = [
            {
                "title": "后台首页",
                "icon": "icon-computer",
                "href": "/proxy/main.html",
                "spread": false
            },

            {
                "title": "加盟商管理",
                "icon": "&#xe632;",
                "href": "javascript:;",
                "spread": false,
                "children": [
                    {
                        "title": "经纪会员",
                        "href": "/proxy/jingji.html",
                        "icon": "",
                        "spread": false
                    },
                    {
                        "title": "机构代理",
                        "href": "/proxy/jigou.html",
                        "icon": "",
                        "spread": false
                    },
                    {
                        "title": "居间代理",
                        "href": "/proxy/jujian.html",
                        "icon": "",
                        "spread": false
                    },
                ]
            },

            {
                "title": "客户管理",
                "icon": "&#xe633;",
                "href": "/proxy/clients.html",
                "spread": false,
            },
            // {
            //     "title": "权限管理",
            //     "icon": "&#xe634;",
            //     "href": "/proxy/permission.html",
            //     "spread": false,
            // },
            {
                "title": "保证金监控",
                "icon": "&#xe635;",
                "href": "/proxy/baozheng.html",
                "spread": false,
            },
            {
                "title": "加盟商监控",
                "icon": "&#xe636;",
                "href": "/proxy/jiameng.html",
                "spread": false,
            },
            {
                "title": "客户风控",
                "icon": "&#xe637;",
                "href": "/proxy/fengkong.html",
                "spread": false,
            },
            {
                "title": "重庆时时彩",
                "icon": "&#xe638;",
                "href": "/proxy/caipiao.html?type=cqssc",
                "spread": false,
                // "children" : [
                //     {
                //         title : "重庆时时彩",
                //         icon : "",
                //         href : "/proxy/caipiao.html?type=cqssc",
                //     },
                //     // {
                //     //     title : "北京快乐8",
                //     //     href : "/proxy/caipiao.html?type=bjkl8"
                //     // }
                // ]
            },
            {
                title: "交易明细",
                icon: "&#xe641;",
                href: "/proxy/order_list.html",
            },
            {
                title: "交易汇总",
                icon: "&#xe642;",
                href: "/proxy/huizong.html",
            },
            {
                title: "客户报表",
                icon: "&#xe643;",
                href: "javascript:;",
                children: [
                    {
                        title: "成交报表",
                        href: "/proxy/chengjiao.html"
                    },
                    {
                        title: "开奖统计",
                        href: "/proxy/kaijiang.html"
                    },
                    {
                        title: "订货统计",
                        href: "/proxy/dinghuo.html"
                    }
                ]
            },
            {
                title: "签约",
                icon: "&#xe644;",
                href: "/proxy/qianyue.html",
            },
            {
                title : "出金",
                icon : "&#xe645",
                href : "/proxy/chujin.html"
            }

        ];

        if (proxyUser.type == 'jingji') {
            ret[1].children.splice(0, 1);
        }
        if (proxyUser.type == 'jigou') {
            ret[1].children.splice(0, 2);
        }
        if (proxyUser.type == 'jujian') {
            ret.splice(1, 1);
        }
        if(proxyUser.id == 1){
            ret[1].children.unshift({
                title : "综合会员",
                href : "/proxy/zonghe.html"
            });
        }

        if (proxyUser.type != 'normal' && proxyUser.type != 'admin') {
            let index = ret.findIndex(item => item.title == '客户报表')
            ret[index].children.splice(0, 1);

            //删除加盟商监控
            index = ret.findIndex(item => item.title == '加盟商监控');
            ret.splice(index,1);
        }

        if(proxyUser.id == 1){
            ret.push({
                title : "出金管理",
                href : "/proxy/cash_list.html?status=-1",
                icon : '&#xe631'
            });
        }


        return ret;
    }


    /**
     * 修改登录密码
     */
    async modify_self_login(
        proxyUser : ProxyUser,
        oldpass?,
        pass?,
        confirm?
    ){
        if(confirm != pass){
            return failed("两次输入的密码不一样");
        }

        if(proxyUser.password != oldpass){
            return failed("旧密码输入错误");
        }

        if(pass.length < 6){
            return failed();
        }

        try{
            proxyUser.password = pass;
            await X.save(proxyUser);
            return success();
        }
        catch(e){
            return failed();
        }

    }

    async modify_self_pay(
        proxyUser : ProxyUser,
        oldpass?,
        pass?,
        confirm?
    ){
        console.log(confirm,pass)
        if(confirm != pass){
            return failed("两次输入的密码不一样");
        }

        if(proxyUser.pay_password != oldpass){
            return failed("旧密码输入错误");
        }

        if(pass.length < 6){
            return failed();
        }

        try{
            proxyUser.pay_password = pass;
            await X.save(proxyUser);
            return success();
        }
        catch(e){
            return failed();
        }

    }


    async changeProxyParent(
        proxyUser: ProxyUser,
        id: number,
        parent_id: number,
        type: string
    ) {
        let child: any;
        if (type == 'member') {
            //只有管理员有权限转移会员
            if(proxyUser.id != 1){
                return failed();
            }
            child = await X.of(ProxyMember).findOne(id);
        }
        else {
            child = await X.of(ProxyUser).findOne(id);
        }
        let parent = await X.of(ProxyUser).findOne(parent_id);
        if (!child || !parent) {
            return failed();
        }
        child.parent_id = parent_id;
        await X.save(child);
        return success();
    }


    async addCash(
        proxyUser : ProxyUser,
        money,
    ){
        money = Number(money);
        if(money !== money || money <= 0
            || money > proxyUser.money - proxyUser.limit_money
        ){
            return failed("请填写正确的出金金额");
        }
        let count = await X.of(ProxyCash).count({
            where : {
                proxy_id : proxyUser.id,
                status : CashStatus.notdeal
            }
        });
        if(count > 0){
            return failed("你不能同时发起多个出金请求");
        }
        let item = new ProxyCash;
        item.money = money;
        item.status = CashStatus.notdeal;
        item.add_time = time();
        item.proxy_id = proxyUser.id;
        item.before_money = proxyUser.money;
        item.after_money = proxyUser.money - money;
        await X.save(item);
        return success();
        // if(X.of(ProxyCash).fin)
    }


    async changeCashStatus(
        proxyUser : ProxyUser,
        id?,
        value?
    ){
        if(!id){
            return failed();
        }
        if(proxyUser.id != 1){
            return failed();
        }
        let item = await X.of(ProxyCash).findOne(id);
        if(!item){
            return failed();
        }
        item.status = value;
        await X.save(item);
        return success();
    }
}
